package com.heima.gateway.filter;

import com.heima.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.List;

/*
全局过滤器，校验token是否有效
 */
@Component
@Slf4j
public class AuthorizeFilter implements GlobalFilter, Ordered {
    /**
     * 执行过滤的方法
     * @param exchange 交换机，可以获取请求和响应对象
     * @param chain 过滤器链
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
       //TODO
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //获取路径
        String path = request.getURI().getPath();
        log.info("请求路径:{}",path);
        List<String> allowedPaths = Arrays.asList("/login", "/logout", "/wemedia/login", "/wm_user/login", "/wm_user/logout", "/wm_user/register");
        if (allowedPaths.stream().anyMatch(path::contains)) {
            // 放行
            return chain.filter(exchange);
        }
        //获取令牌
        String token = request.getHeaders().getFirst("token");
        if (token == null) {
            response.setStatusCode(org.springframework.http.HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //校验令牌
        try {
            //解析token
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            //校验token是否过期
            int result = AppJwtUtil.verifyToken(claimsBody);
            if (result == 1 || result == 2) {
                response.setStatusCode(org.springframework.http.HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatusCode(org.springframework.http.HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        return chain.filter(exchange);
    }
    /**
     * 过滤的执行的优先级，返回值越小优先级越高
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
